<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\WebSocket;

use App\WebSocket\Chat\HomeController;
use Swoft\Http\Message\Request;
use Swoft\WebSocket\Server\Annotation\Mapping\OnOpen;
use Swoft\WebSocket\Server\Annotation\Mapping\WsModule;
use Swoft\WebSocket\Server\MessageParser\JsonParser;
use App\WebSocket\Chat\ServerController;
use App\WebSocket\Chat\ClientController;
use App\WebSocket\Chat\LoginController;
use Swoft\Redis\Redis;
use Tool\AjaxReturn;
use Swoft\WebSocket\Server\Annotation\Mapping\OnClose;
use Swoole\WebSocket\Server;

/**
 * Class ChatModule
 * @WsModule(
 *     "/chat",
 *     messageParser=JsonParser::class,
 *     controllers={HomeController::class,
 *      ServerController::class,
 *      ClientController::class,
 *      LoginController::class
 *    }
 * )
 */
class ChatModule
{
    /**
     * @OnOpen()
     * @param Request $request
     * @param int $fd
     * @return array
     */
    public function onOpen(Request $request, int $fd): array
    {
        
        vdump( $request->getHeader("token"));
        $token = $request->getHeader("token");
        
        if (empty($token[0])) {
            server()->disconnect($fd, 0);
            return [];
        }
      
        $userId = Redis::get($token[0]);
        
        if (!$userId) {
            server()->disconnect($fd, 0);
            return [];
        }
        
        // 在线人数
        Redis::hSet('fd', (string)$userId, $fd);
        
        vdump(Redis::hGetAll('fd'));
        
        return AjaxReturn::sendWebsocketData(['fd' => $request->getFd(), 'secret_key' => md5(config('app.salt').$token[0])]);
    }
    
    /**
     * @OnClose()
     * @return array
     */
    public function close(Server $server, int $fd): void
    {
//         $fd = Redis::hGetAll('fd');
        
        
    }
}
